from collections import Counter

# 转化带有赔数的数据格式{类型:[赔率,赔数]}
# dx = {"0球":10.5,"1球":6.2}
def to_pei(dx):
    # 排序
    ds = sorted(dx.items(), key=lambda x: x[1], reverse=False)
    # print(ds)
    res = {}
    for i in range(len(ds)):
        d = ds[i]
        res[d[0]] = (d[1], i + 1)
    # print(res)
    return res

# 赔数的数据格式[[赔率,类型]}
# dx = [(3.3,"s2")，(3.5,"s3"),(4,5,"s1")....],列表序号表示赔数，
def to_pei_list(dx):
    # dx 的格式：{"s0":12.4,"s1":6.4,"s2":3.2,.....}
    # 排序: 升  ds = [("s2",3.2),("s3",3.4),....]
    ds = sorted(dx.items(), key=lambda x: x[1], reverse=False)
    return ds

# 球方差
def manual_variance(data):
    n = len(data)
    variance = max(data)
    if n > 1:
        avg = sum(data) / n
        variance = round(sum([(x - avg) ** 2 for x in data]) / (n - 1),2)
    return variance

'''
统计最大间隔
dx：[0,1,1,1,0]
0表示不中，1表示中
'''
def tj(dx):
    # 查看一下多少次中奖一次，间隔多少次
    r = []
    a = 0
    dxsum = sum(dx)
    mzl = 0
    maxjg = 0
    avgjg = 0
    variance = 0
    crrjg = 0
    for d in dx:
        if d == 0:
            a += 1
        else:
            r.append(a)
            a = 0
    dxres = Counter(dx)
    if dxsum:
        mzl = round(dxres.get(1)/len(dx),4)
        maxjg = max(r)
        avgjg = round(sum(r)/len(r),2)
        variance = manual_variance(r)
        crrjg = r[0]
        # print("统计：", dxres,"命中率：",mzl)
        # print("最大间隔：", maxjg)
        # print("平均间隔：", avgjg)
        # print("方差：", variance)
        # print("间隔多久中：", crrjg)

    # 命中率,最大间隔,平均间隔,方差
    return mzl,maxjg,avgjg,variance,crrjg

# 胜平负分析数据格式化数据[12,11,5,3,5,7],是否售卖数据，如果是，就没有比赛结果
def formatHDAData(m,isselling=False):
    oddsHistory = m.get("fixedBonus").get("oddsHistory")
    # 开奖信息
    sectionsNo999 = m.get("sectionsNo999")
    matchResultList = m.get("fixedBonus").get("matchResultList")
    singleList = oddsHistory.get("singleList")
    leagueAbbName = oddsHistory.get("leagueAbbName")
    # 将开放单关的信息放到列表里面
    slist = []
    for s in singleList:
        if s.get("single") == 1:
            slist.append(s.get("poolCode"))
    #   H胜，D平,A负,C异常
    spfr = "c"
    hspfr = "c"
    if matchResultList:
        for r in matchResultList:
            if r.get("code") == 'HAD':
                spfr = r.get("combination").lower()
            if r.get("code") == 'HHAD':
                hspfr = r.get("combination").lower()

    if isselling:
        awayTeamAbbName = m.get("awayTeamAbbName")
        homeTeamAbbName = m.get("homeTeamAbbName")
    else:
        awayTeamAbbName = m.get("awayTeam")
        homeTeamAbbName = m.get("homeTeam")
    # 胜平负
    hadList = oddsHistory.get("hadList")
    had_data = [0,0,0]
    spf_result = [spfr,0,0,-1]  # 结果，陪数，赔率
    # 有可能没有开设胜平负（只有让球，没有胜平负）
    res_spf = {}
    peid_spf = []
    spfv = []
    if hadList:
        had = hadList[-1]
        spf = {"h": float(had.get("h")), "d": float(had.get("d")), "a": float(had.get("a"))}
        spfv = [float(had.get("h")), float(had.get("d")), float(had.get("a"))]
        # 转化带有赔数的数据格式{"s0":[10.5,6]}
        res_spf = to_pei(spf)
        peid_spf = to_pei_list(spf)
        # 构造开奖结果
        if spfr not in ['c']:
            spf_result = [spfr, res_spf.get(spfr)[1], res_spf.get(spfr)[0],spfTo012(spfr)]  # 胜平负开奖结果（结果，陪数，赔率）
        had_data = [float(had.get("h")),float(had.get("d")),float(had.get("a"))]
    # 让球胜平负
    hhad = oddsHistory.get("hhadList")[-1]
    # 让球数
    goalLine = hhad.get("goalLine")
    hspf = {"h": float(hhad.get("h")), "d": float(hhad.get("d")), "a": float(hhad.get("a"))}
    hspfv = [float(hhad.get("h")), float(hhad.get("d")), float(hhad.get("a"))]
    # 转化带有赔数的数据格式{"s0":[10.5,6]}
    res_hspf = to_pei(hspf)
    peid_hspf = to_pei_list(hspf)
    # 构造开奖结果
    hspf_result = [hspfr, 0, 0,spfTo012(hspfr)]  # 结果，陪数，赔率,结果（012,0：胜，1：平，2：负）
    if hspfr not in ['c']:
        hspf_result = [hspfr,res_hspf.get(hspfr)[1],res_hspf.get(hspfr)[0],spfTo012(hspfr)]      # 让球胜平负开奖结果（结果，陪数，赔率）
    hhad_data = [float(hhad.get("h")),float(hhad.get("d")),float(hhad.get("a"))]

    # 加上半全场的数据拿去分析
    hafuLists = oddsHistory.get("hafuList")
    hafu_data = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    if hafuLists:
        hafuList = hafuLists[-1]
        hh = float(hafuList.get("hh"))
        hd = float(hafuList.get("hd"))
        ha = float(hafuList.get("ha"))
        dh = float(hafuList.get("dh"))
        dd = float(hafuList.get("dd"))
        da = float(hafuList.get("da"))
        ah = float(hafuList.get("ah"))
        ad = float(hafuList.get("ad"))
        aa = float(hafuList.get("aa"))
        hafu_data = [hh,hd,ha,dh,dd,da,ah,ad,aa]

    # 构造分析数据
    data = had_data + hhad_data+[int(goalLine)]+hafu_data

    # data 是拿去比对的数据，方便查找相同数据的比赛
    res = {"matchNumStr": m.get("matchNumStr"),"singleList":slist, "goalLine": goalLine,"leagueAbbName":leagueAbbName,"awayTeamAbbName": awayTeamAbbName, "homeTeamAbbName": homeTeamAbbName,
             "details": {"had": res_spf, "hspf": res_hspf}, "matchResult":{"spf":spf_result,"hspf":hspf_result,"sectionsNo999":sectionsNo999},"peid_spf": peid_spf, "peid_hspf": peid_hspf,
             "spfv": spfv, "hspfv": hspfv, "matchDate": m.get("matchDate"), "matchTime": m.get("matchTime"),
             "matchId": m.get("matchId"),"data": data}
    return res

# 总进球分析数据格式化数据[12,11,5,3,5,7,9,15],是否售卖数据，如果是，就没有比赛结果
def formatTTGData(m,isselling=False):
    sectionsNo999 = m.get("sectionsNo999")
    oddsHistory = m.get("fixedBonus").get("oddsHistory")
    # 开奖信息
    matchResultList = m.get("fixedBonus").get("matchResultList")
    #   总进球
    t = -1
    grs = list(filter(lambda x:x.get("code") == 'TTG',matchResultList))
    if len(grs) > 0:
        r = grs[0]
        tr = r.get("combination")
        if tr == "7+":
            t = 7
        else:
            t = int(tr)

    if isselling:
        awayTeamAbbName = m.get("awayTeamAbbName")
        homeTeamAbbName = m.get("homeTeamAbbName")
    else:
        awayTeamAbbName = m.get("awayTeam")
        homeTeamAbbName = m.get("homeTeam")
    # 开奖最后赔率
    ttg = oddsHistory.get("ttgList")[-1]
    qiu = {"s0": float(ttg.get("s0")), "s1": float(ttg.get("s1")),"s2": float(ttg.get("s2")),"s3": float(ttg.get("s3")),"s4": float(ttg.get("s4")),"s5": float(ttg.get("s5")),"s6": float(ttg.get("s6")),"s7": float(ttg.get("s7"))}
    qiuv = [float(ttg.get("s0")), float(ttg.get("s1")),float(ttg.get("s2")),float(ttg.get("s3")),float(ttg.get("s4")),float(ttg.get("s5")),float(ttg.get("s6")),float(ttg.get("s7"))]
    # 转化带有赔数的数据格式{"s0":[10.5,6]}
    res_qiu = to_pei(qiu)
    # [("s2",3.2),("s3",3.4),....]
    peid_qiu = to_pei_list(qiu)
    s = f's{t}'
    pei = 0
    if not isselling:
        if t == -1:     # 防止比赛已经结束，但是没有开奖结果的时候
            return None
        else:
            pei = res_qiu.get(s)[1]

    # data 是拿去比对的数据，方便查找相同数据的比赛
    res = {"info": {"matchNumStr": m.get("matchNumStr"), "awayTeamAbbName": awayTeamAbbName,
                    "homeTeamAbbName": homeTeamAbbName, "pei": pei, "ttg": t, "sectionsNo999": sectionsNo999,
                    "details": res_qiu, "matchId": m.get("matchId"),
                    "matchDate": m.get("matchDate"), "matchTime": m.get("matchTime")}, "data": qiuv, "peid": peid_qiu}

    return res

# 胜平负转012,  0：胜。1：平，2：负，方便统计显示
def spfTo012(a):
    r = -1
    if a == 'h':
        r = 0
    elif a == 'd':
        r = 1
    elif a == 'a':
        r = 2
    else:
        r = -1
    return r


#  开奖数据格式化
def formatKJData(ds):
    rs = []
    for m in ds:
        # 基本信息
        matchId = m.get("matchId")
        goalLine = m.get("goalLine")
        matchNum = m.get("matchNum")
        matchNumStr = m.get("matchNumStr")
        matchTime = m.get("matchTime")
        homeTeam = m.get("homeTeam")
        awayTeam = m.get("awayTeam")
        bettingSingle = m.get("bettingSingle")
        base_info = {"matchId":matchId,"goalLine":goalLine,"matchNum":matchNum,"matchNumStr":matchNumStr,
                     "homeTeam":homeTeam,"awayTeam":awayTeam,"bettingSingle":bettingSingle,"matchTime":matchTime}
        info = {"base_info": base_info}
        # 开奖信息
        sectionsNo1 = m.get("sectionsNo1")
        sectionsNo999 = m.get("sectionsNo999")
        kaijiang = {"sectionsNo1":sectionsNo1,"sectionsNo999":sectionsNo999}
        matchResultList = m.get("fixedBonus").get("matchResultList")
        oddsHistory = m.get("fixedBonus").get("oddsHistory")
        if matchResultList:
            for r in matchResultList:
                ct = r.get("code").lower()+"List"
                r["ps"] = oddsHistory.get(ct)
                kaijiang[r.get("code")] = r
        info["kaij"] = kaijiang
        rs.append(info)
    return rs



# 半全场分析数据格式化数据,isselling是否售卖数据，true是，false就没有比赛结果
def formatHAFUData(m,isselling=False):
    sectionsNo999 = m.get("sectionsNo999")
    oddsHistory = m.get("fixedBonus").get("oddsHistory")
    # 开奖信息
    matchResultList = m.get("fixedBonus").get("matchResultList")
    #   半全场
    t = 'hh'
    grs = list(filter(lambda x:x.get("code") == 'HAFU',matchResultList))
    if len(grs) > 0:
        t = grs[0].get("combination").replace(":","").lower()

    if isselling:
        awayTeamAbbName = m.get("awayTeamAbbName")
        homeTeamAbbName = m.get("homeTeamAbbName")
    else:
        awayTeamAbbName = m.get("awayTeam")
        homeTeamAbbName = m.get("homeTeam")
    # 开奖最后赔率
    orgs = oddsHistory.get("hafuList")
    if len(orgs) > 1:
        org = orgs[-1]
    elif len(orgs) == 1:
        org = orgs[0]
    else:
        return None
    qiu = {"hh": float(org.get("hh")), "hd": float(org.get("hd")), "ha": float(org.get("ha")),
           "dh": float(org.get("dh")), "dd": float(org.get("dd")), "da": float(org.get("da")),
           "ah": float(org.get("ah")), "ad": float(org.get("ad")), "aa": float(org.get("aa"))}
    qiuv = [float(org.get("hh")), float(org.get("hd")), float(org.get("ha")),
            float(org.get("dh")), float(org.get("dd")), float(org.get("da")),
            float(org.get("ah")), float(org.get("ad")), float(org.get("aa"))]

    # 转化带有赔数的数据格式{"s0":[10.5,6]}
    res_qiu = to_pei(qiu)
    peid_qiu = to_pei_list(qiu)
    pei = 0
    if not isselling:
        pei = res_qiu.get(t)[1]

    # data 是拿去比对的数据，方便查找相同数据的比赛
    res = {"info": {"matchNumStr": m.get("matchNumStr"), "awayTeamAbbName": awayTeamAbbName,
                    "homeTeamAbbName": homeTeamAbbName, "pei": pei, "result": t, "sectionsNo999": sectionsNo999,
                    "details": res_qiu, "matchId": m.get("matchId"),
                    "matchDate": m.get("matchDate"), "matchTime": m.get("matchTime")}, "data": qiuv, "peid": peid_qiu}

    return res

def getHAFUindex(n):
    listN = ["hh","hd","ha","dh","dd","da","ah","ad","aa"]
    return listN.index(n)

# 根据比分结果，得出开奖结果，胜平负，让球胜平负，进球，半全场，比分
def getMatchResult(sectionsNo1,sectionsNo999,goalLine):
    res = {}
    # 胜平负
    scores = [int(a) for a in sectionsNo999.split(":")]
    if scores[0] < scores[1]:
        res["had"] = "a"
    elif scores[0] > scores[1]:
        res["had"] = "h"
    else:
        res["had"] = "d"

    # 让球胜平负
    s = scores[0]
    if goalLine[0] == "-":
        s -= int(goalLine[1])
    else:
        s += int(goalLine[1])

    if s < scores[1]:
        res["hhad"] = "a"
    elif s > scores[1]:
        res["hhad"] = "h"
    else:
        res["hhad"] = "d"

    # 全半场
    scoresNo1 = [int(a) for a in sectionsNo1.split(":")]
    if scoresNo1[0] < scoresNo1[1]:
        hafu_res = "a"
    elif scoresNo1[0] > scoresNo1[1]:
        hafu_res = "h"
    else:
        hafu_res = "d"
    res["hafu"] = hafu_res + res.get("had")

    # 总进球(注意7+的情况)
    t = scores[0]+scores[1]
    if t < 7:
        res["ttg"] = "s" + str(t)
    else:
        res["ttg"] = "s7"
    # 比分
    if scores[0] < 10:
        b1 = "s0" + str(scores[0])
    else:
        b1 = "s" + str(scores[0])
    if scores[1] < 10:
        b2 = "s0" + str(scores[1])
    else:
        b2 = "s" + str(scores[1])

    res["crs"] = b1 + b2

    return res